package edu.android.proyecto.sqliteclient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
public class Database
{
	private static String DB_PATH = "/data/data/edu.android.proyecto/databases/";
	private static String DB_NAME = "deliccio";
	// private Context context;
	static public void createDataBase(Context context) throws IOException
	{
		boolean dbExist = false; // checkDataBase();
		if (!dbExist)
		{
			try
			{
				copyDataBase(context);
			}
			catch (IOException e)
			{
				throw new Error("Error copying database: " + e.getMessage());
			}
		}
	}
	static public boolean checkDataBase()
	{
		SQLiteDatabase checkDB = null;
		try
		{
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
		}
		catch (SQLiteException e)
		{
		}
		if (checkDB != null)
		{
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}
	static public void copyDataBase(Context context) throws IOException
	{
		File dir = new File(DB_PATH);
		if (!dir.exists())
			dir.mkdir();
		InputStream myInput = context.getAssets().open("deliccio");
		/*
		 * InputStream myInput2 = context.getAssets().open("database_ab");
		 * InputStream myInput3 = context.getAssets().open("database_ac");
		 */
		String outFileName = DB_PATH + DB_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0)
		{
			myOutput.write(buffer, 0, length);
		}/*
		  * while ((length = myInput2.read(buffer))>0){ myOutput.write(buffer,
		  * 0, length); } while ((length = myInput3.read(buffer))>0){
		  * myOutput.write(buffer, 0, length); }
		  */
		myOutput.flush();
		myOutput.close();
		myInput.close();
		// myInput2.close();
	}
}